package UDP.Demo1;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPServer {
    public static void main(String[] args) {
        try {
            // 创建DatagramSocket，监听端口9876
            DatagramSocket serverSocket = new DatagramSocket(9876);
            System.out.println("UDP服务器已启动，等待客户端消息...");

            while (true) {
                // 准备接收数据包
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // 接收客户端数据
                serverSocket.receive(receivePacket);
                String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                System.out.println("收到来自客户端 " + clientAddress + ":" + clientPort + " 的消息: " + message);

                // 发送响应给客户端
                String response = "服务器已收到你的消息: " + message;
                byte[] sendData = response.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(
                        sendData, sendData.length, clientAddress, clientPort);
                serverSocket.send(sendPacket);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
